/*
 * <applet code="applets.simple.HelloWorld.class" width="200" height="200"></applet>
 */

package applets.simple.etu;

import java.applet.AppletContext;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;

/**
 * Exemple d'applet
 * 
 * @author lom
 */
public class HelloWorld extends java.applet.Applet {

	private static final long serialVersionUID = 1L;
	private StringBuffer buffer;
	int curX = 0, curY = 0;

	@Override
	public void init() {
		buffer = new StringBuffer();
		Font f = new Font("Helvetica", Font.TRUETYPE_FONT, 12);
		setFont(f);
		addItem("Initializing...");
		// test d'affichage dans la console
		String name = getParameter("Etu1");
		addItem("Nom : " + name);
		if (name == null) {
			int count = Integer.parseInt(getParameter("Count"));
			addItem("Nombre d'étudiants :" + count);
		}
		//System.out.println("Initialisation");
	}

	@Override
	public void start() {
		addItem("Start: Hello World!");
		
	}

	@Override
	public void stop() {
		addItem("Stop: Bye!");
	}

	@Override
	public void destroy() {
		addItem("Destruction");
	}

	private void addItem(String newWord) {
		//System.out.println(newWord);
		buffer.append(newWord + "\n");
		// repaint();
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		// Dessine un rectangle autour de l'aire d'affichage de l'applet.
		g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
		// g.drawString(buffer.toString(), 10, 10);
		afficheText(buffer.toString(), g);
		buffer.delete(0, buffer.length()-1);
		g.drawString("Une ligne : ", 25, 100);
		g.drawLine(100, 100, 200, 100);
		g.drawString("Un rectangle : ", 25, 150);
		g.drawRect(125, 150, 100, 100);
		// g.drawString("Un rectangle  3D: ", 25, 250);
		// g.draw3DRect(125, 250, 100, 100, false);
		g.drawString("Un cercle : ", 25, 200);
		g.drawOval(125, 200, 50, 50);
		
		AppletContext context = getAppletContext();
		URL url;
		try {
			url = new URL("http://www.nyt.com");
			context.showDocument(url);
		} catch (MalformedURLException e) {
			g.drawString("Probleme de chargement :" + e.getMessage(), 0, 450);
		}
		
		

	}

	private void afficheText(String msg, Graphics g) {
		FontMetrics fm = g.getFontMetrics();
		curY += fm.getHeight();
		StringTokenizer tokens = new StringTokenizer(msg, "\n");
		while (tokens.hasMoreTokens()) {
			String s = tokens.nextToken();
			g.drawString(s, curX, curY);
			curY += fm.getHeight();
			// curX=fm.stringWidth(s);
		}
		curY = 0;
	}
}
